/*
 *  modal滑动关闭模型
 */
import { IModalEngineProps } from './type';

const animationCssText = (id: string, height: any) => {
  return `
      @keyframes ${id} {
       0% {
         transform: translateY(0px);
        }
        100%{
          transform: translateY(${height}px);
        }
      }
    `;
};

export class ModalEngine {
  className: string = ''; // modal类名

  modalHeight: number = 0; // 模态框高度

  styleId: string = ''; //style标签Id

  animateId: string = ''; //动画Id

  constructor(props: IModalEngineProps) {
    if (props) {
      this.init(props);
    }
  }

  init(props: IModalEngineProps) {
    if (props?.className) {
      this.className = props.className;
    }

    if (props?.styleId) {
      this.styleId = props.styleId;
    }

    if (props?.animateId) {
      this.animateId = props.animateId;
    }
  }

  /* 加载style标签 */
  mount() {
    this.dynamicLoadStyle();
  }

  /* 卸载 */
  unmount() {
    let removeAnimation = document.getElementById(this.styleId);

    if (removeAnimation) {
      removeAnimation.remove();
    }

    this.className = '';
    this.modalHeight = 0;
    this.styleId = '';
    this.animateId = '';
  }

  /* 动态加加载style标签 */
  dynamicLoadStyle() {
    let removeAnimation = document.getElementById(this.styleId);
    if (removeAnimation) {
      removeAnimation.remove();
    }
    let initHeight = (document.getElementsByClassName(this.className)[0] as any)
      ?.offsetHeight;

    this.modalHeight = initHeight;

    if (initHeight && this.animateId) {
      let cssText = animationCssText(this.animateId, initHeight);

      let modalAnimationStyle = document.createElement('style');

      modalAnimationStyle.setAttribute('type', 'text/css');
      modalAnimationStyle.setAttribute('id', this.styleId);

      modalAnimationStyle.innerHTML = cssText;

      let head: any = document.getElementsByTagName('head').item(0);
      head.appendChild(modalAnimationStyle);
    }
  }

  /* 关闭弹窗 */
  closeModal(
    e: React.MouseEvent<HTMLElement, MouseEvent>,
    className: string,
    closeFnc?: Function,
  ) {
    const modal: Element | any = document
      .getElementsByClassName(className)[0]
      ?.getElementsByClassName('ant-modal-content')[0];

    if (closeFnc && modal) {
      modal.style.animation = `${this.animateId} 1s`;

      setTimeout(() => {
        if (modal && modal?.style && modal?.style?.animation) {
          modal.style.animation = '';
          closeFnc(e);
        }
      }, 900);
    }
  }
}
